package org.gangcai.mac.shop.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.CoordinatorLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.gangcai.mac.shop.R;
import org.gangcai.mac.shop.activity.BrandActivity;
import org.gangcai.mac.shop.activity.SPProductListActivity;
import org.gangcai.mac.shop.activity.ShopDetailActivity;
import org.gangcai.mac.shop.adapter.HeaderAndFooterAdapter;
import org.gangcai.mac.shop.adapter.PullToRefreshAdapter;
import org.gangcai.mac.shop.api.AppAPI;
import org.gangcai.mac.shop.bean.CategoryBean;
import org.gangcai.mac.shop.bean.DynamicBean;
import org.gangcai.mac.shop.bean.IndexBean;
import org.gangcai.mac.shop.bean.UpdateShopData;
import org.gangcai.mac.shop.constants.Constant;
import org.gangcai.mac.shop.manager.RetrofitManager;
import org.gangcai.mac.shop.manager.RetrofitManagers;
import org.gangcai.mac.shop.oberver.CommonObserver;
import org.gangcai.mac.shop.rxlife.RxFragment;
import org.gangcai.mac.shop.utils.PromptDialogUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.android.schedulers.AndroidSchedulers;
import me.leefeng.promptlibrary.PromptDialog;

/**
 * 商品界面
 */
public class CategoryFragment extends RxFragment implements MultiItemTypeAdapter.OnItemClickListener, OnRefreshListener {
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    Unbinder unbinder;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.recyclerview1)
    RecyclerView recyclerview1;
    @BindView(R.id.category_right)
    TextView category_right;
    ArrayList<CategoryBean.CateBean> datalist = new ArrayList<>();
    ArrayList<CategoryBean.ChildrenBean> datalist1 = new ArrayList<>();
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    private String mParam1;
    private String mParam2;
    private CommonAdapter<CategoryBean.CateBean> adapter;
//    private CommonAdapter<CategoryBean.ChildrenBean> adapter1;
    private HeaderAndFooterAdapter headerAndFooterAdapter;
    private PromptDialog prompDialog;

    public CategoryFragment() {
    }

    public static CategoryFragment newInstance(String param1, String param2) {
        CategoryFragment fragment = new CategoryFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        EventBus.getDefault().register(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_category, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        prompDialog = PromptDialogUtils.getPrompDialog(getActivity());
        recyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
        initView();
        loadData();
    }

    private void loadData() {
        LogUtils.e("loadCategoryFragment");
        RetrofitManagers.getInstance().create(AppAPI.class).category("category")
                .observeOn(AndroidSchedulers.mainThread())
                .compose(this.<CategoryBean>bindToLifecycle())
                .subscribe(new CommonObserver<CategoryBean>(refreshLayout) {
                    @Override
                    public void onSuccess(CategoryBean value) {
                        if (value.getCode() == 101) {
                            datalist.clear();
                            datalist1.clear();
                            value.getInfo().get(0).setFlag(true);
                            datalist.addAll(value.getInfo());
                            datalist1.addAll(value.getInfo().get(0).getChildren());
                            adapter.notifyDataSetChanged();
                            headerAndFooterAdapter.notifyDataSetChanged();
                        }
                    }

                });
    }

    private void

    initView() {
        adapter = new CommonAdapter<CategoryBean.CateBean>(this.getContext(), R.layout.fragment_cate_recyclerview_item, datalist) {
            @Override
            protected void convert(ViewHolder holder, CategoryBean.CateBean o, int position) {
                if(datalist.get(position).isFlag()){
                    holder.setBackgroundColor(R.id.shop_item_root, 0xffe8e8e8);
                    holder.setTextColor(R.id.cateTitle, 0xffDE3535);
                }else {
                    holder.setBackgroundColor(R.id.shop_item_root, 0xFFFFFFFF);
                    holder.setTextColor(R.id.cateTitle, 0xff515151);
                }
                holder.setText(R.id.cateTitle, o.getName());
            }

        };
        headerAndFooterAdapter = new HeaderAndFooterAdapter(datalist1);
        View headView = getLayoutInflater().inflate(R.layout.catalog_head_view, (ViewGroup) recyclerview1.getParent(), false);
        headerAndFooterAdapter.addHeaderView(headView);
        recyclerview.setLayoutManager(new GridLayoutManager(this.getContext(), 1));
        recyclerview1.setLayoutManager(new GridLayoutManager(this.getContext(), 2));
        recyclerview.setAdapter(adapter);
        recyclerview1.setAdapter(headerAndFooterAdapter);

        adapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener(){
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                datalist1.clear();
                datalist1.addAll(datalist.get(position).getChildren());
                headerAndFooterAdapter.notifyDataSetChanged();
                for (int i = 0; i < datalist.size(); i++) {
                    if (i == position) {
                        datalist.get( i ).setFlag( true );
                    } else {
                        datalist.get( i ).setFlag( false );
                    }
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });

        headerAndFooterAdapter.setOnItemClickListener(new HeaderAndFooterAdapter.OnItemClickListener(){

            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Bundle bundle = new Bundle();
                bundle.putString("cat_id", datalist1.get(position).getId());
                ActivityUtils.startActivity(bundle, getActivity(), SPProductListActivity.class);
            }
        });

        category_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ActivityUtils.startActivity(getActivity(), BrandActivity.class);

            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
        Bundle bundle = new Bundle();
        bundle.putString("id", datalist.get(position).getId());
        ActivityUtils.startActivity(bundle, this.getActivity(), ShopDetailActivity.class);
    }

    @Override
    public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
        return false;
    }

    @Subscribe
    public void onEvent(UpdateShopData data) {
        loadData();
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        loadData();
    }
}
